package com.hdaccp.news.controller;
import com.hdaccp.news.dao.NewsDao;
import com.hdaccp.news.service.NewsService;
import com.hdaccp.pojo.po.News;
import org.hibernate.validator.constraints.EAN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/news")
public class NewsController {

    @Autowired
    private NewsDao newsDao ;
    @Autowired
    private NewsService newsService ;

    @RequestMapping("/query")
    public List<News> query(){
        return newsDao.findAll() ;
    }

    @RequestMapping("/getOne/{newsId}")
    public News getOne(@PathVariable("newsId") int newsId){
        return newsDao.findById(newsId).get() ;
    }

    @RequestMapping("/queryPage/{cpage}/{pagesize}")
    public List<News> queryPage(@PathVariable("cpage") int cpage,@PathVariable("pagesize") int pagesize) {
        return newsService.queryPage(cpage,pagesize) ;
    }

    @RequestMapping("/save/{title}/{content}")
    public String  save(@PathVariable("title") String title,@PathVariable("content") String content) {
        String msg = "success" ;
        String createTime =  new SimpleDateFormat("yyyy-MM-dd").format(new Date()) ;
        News news = new News() ;
        news.setContent(content);
        news.setTitle(title);
        news.setCreateTime(createTime);
        try {
            newsDao.save(news) ;
        } catch (Exception e){
            msg = "shibai" ;
        }
        return msg ;
    }

    @RequestMapping("/update/{id}/{title}/{content}")
    public String  update(@PathVariable int id,@PathVariable("title") String title,@PathVariable("content") String content) {
        String msg = "success" ;
        News news = newsDao.findById(id).get() ;
        news.setTitle(title);
        news.setContent(content);
        try {
            newsDao.save(news) ;
        } catch (Exception e){
            msg = "shibai" ;
        }
        return msg ;
    }


    @RequestMapping("/del/{id}")
    public String  update(@PathVariable int id) {
        String msg = "success" ;

        try {
            newsDao.deleteById(id);
        } catch (Exception e){
            msg = "shibai" ;
        }
        return msg ;
    }
}
